<?php
namespace app\common\model\account;
use think\Model;
use app\common\model\orderdata\Goods;

class AccountSelfUse extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'account_self_use';
    protected $pk = 'Id';

     /**
     * 关联 台账连接表
     * @return [type] [description]
     */
    public function link()
    {
        return $this->hasMany('AccountLink','AccountSelfUseId','Id');
    }
    public function goodinfo()
    {
        return $this->hasone('app\common\model\orderdata\Goods','GoodId','GoodId');
    }

    // 创建产生台账
    public static function createAccount($params)
    {
        if(empty($params['CompanyId'])){
            return moerr('缺少关联企业');
        }
        $selfusefile = ["Type","EquipmentName","EquipmentCode","UseType","UseEndTime","UseUserName","UseUserId","SourceBatchCode"];
        $data = new AccountSelfUse();
        $data->GoodId = $params['GoodId'];
        $data->GoodName = $params['GoodName'];
        $data->BatchCode = $params['BatchCode'];
        $data->AccountTime = $params['AccountTime'];
        $data->EndFlag = isset($params['EndFlag'])?$params['EndFlag']: 0;
        $data->CreatUserId = $params['CreatUserId'];
        $data->UpNote = isset($params['UpNote'])?$params['UpNote']: '';
        $data->UpdateTime = date('Y-m-d H:i:s',time());
        $data->Quantity = $params['Quantity'];
        $data->Unit = $params['Unit'];
        $data->BoxBatchCode = $params['BoxBatchCode'];
        $data->BoxType = $params['BoxType'];
        $data->BoxCount = $params['BoxCount'];
        $data->OrderListId = isset($params['OrderListId'])?$params['OrderListId']:'';
        //自利用字段
        foreach ($selfusefile as $fk => $fv) {
            $data->$fv = empty($params[$fv])?'':trim($params[$fv]);
        }
        if(empty($params['Type'])){
            $data->Type = '处置';
        }
        $data->CompanyId = $params['CompanyId'];
        $data->save();
        return $data->Id;
    }

    /**
     * 获取批次编码
     * @return [type] [description]
     */
    public static function getBatchCode($company_id,$time='',$type=''){
        if(empty($time)){
            $time = time();
        }
        $today = date('Y-m-d',$time);
        if($type!=='利用'){
            $type='处置';
        }
        $count = AccountSelfUse::where('AccountTime', '>', $today)->where('CompanyId', $company_id)->where('Type',$type)->where('AccountTime', '<', $today . ' 24:00')->count();
        $str = $type=='利用'?'LY':'CZ';
        return 'HWZX'.$str.date('YmdHi',$time).sprintf("%03d",$count+1);
    }

    /**
     * 获取包装物的批次编码
     * @return [type] [description]
     */
    public static function getBoxBatchCode($company_id){
        $count = AccountCreate::where('CompanyId',$company_id)->count();
        return $count+1;
    }


}
